package com.bw.ivideoproject.home

import android.content.Intent
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SizeUtils
import com.bw.ivideoproject.R
import com.bw.ivideoproject.databinding.ActivitySearchBinding
import com.bw.ivideoproject.db.entity.HistoryEntity
import com.bw.ivideoproject.wight.FlowLayout
import com.bw.lib_mvvm.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SearchActivity : BaseActivity<ActivitySearchBinding>() {
//    搜索
//    用户中心模块实现
//    应用自升级
//    IM
//    直播
//    热修复
//    内存泄漏
//    金币
//    推送
//    git

    private val padding = SizeUtils.dp2px(5.0F)
    private val viewModel : HomeViewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun initView() {
        binding.flHot.removeAllViews()
        val hotSearch = resources.getStringArray(R.array.hotSearch);
        showFlowSearch(hotSearch,binding.flHot)
    }

    override fun initData() {
        viewModel.getHistorySearch()

        binding.search.setOnClickListener {
            val keyword = binding.etSearch.text.toString()
            if(keyword.isBlank()){
                showMsg("请输入搜索内容")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                withContext(Dispatchers.IO){
                    viewModel.insertSearch(HistoryEntity(0,keyword))
                    withContext(Dispatchers.Main){
                        val intent = Intent(this@SearchActivity, SearchListActivity::class.java).apply {
                            this.putExtra("keyword",keyword)
                        }
                        startActivity(intent)
                    }
                }
            }
            binding.etSearch.setText("")
        }
    }

    override fun bindLayout(): Int {
        return R.layout.activity_search
    }

    override fun handleObserver() {
        super.handleObserver()
        viewModel.searchLiveData.observe(this){
            showFlowSearch(it,binding.flLs)
        }
    }

    private fun showFlowSearch(list:Array<String>, view:FlowLayout){
        list.forEach {
            var textView = TextView(this@SearchActivity)
            textView.text = it
            textView.setBackgroundResource(R.drawable.shape_titlebar)
            textView.setPadding(padding,padding,padding,padding)
            textView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            view.addView(textView)
        }
    }

}